<template>
  <div class="category-tab">
    <div class="operation-bar">
      <!-- 操作按钮区域 -->
      <action-buttons
          :buttons="buttonsConfig"
          @add="handleAdd"
          @delete="handleDelete"
          @edit="handleEdit"
          @import="handleImport"
          @export="handleExport"
          @viewLog="handleViewLog"
      />

      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="请输入分类名称"
            class="search-input"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
        />
      </div>
    </div>
    <div class="main-content">
      <el-tree
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          node-key="id"
          :expand-on-click-node="false"
          :highlight-current="true"
          @node-click="nodeClick"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增分类' : '编辑分类'"
        width="400px"
        align-center
        :close-on-click-modal="false"
        @closed="handleDialogClosed">
      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          style="margin: 20px 20px 20px 0"
          label-width="95px">
        <el-form-item label="上级分类">
          <el-input v-model="parentName" disabled/>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input
              v-model="formData.name"
              placeholder="请输入分类名称"
              maxlength="20"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 引入确认操作弹窗组件 -->
    <ConfirmDialog
        v-model:visible="confirmDialogVisible"
        :action="currentAction"
        @cancel="cancelConfirm"
        @confirm="confirmAction"
    />
  </div>
</template>

<script setup>
import {ref, reactive, watch} from 'vue'
import {Search} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import ActionButtons from "@/components/action-buttons/action-buttons.vue"
import ConfirmDialog from "@/components/action-buttons/confirm-dialog.vue";

// 树形配置
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 树形数据
const treeData = ref([
  {
    id: 1,
    label: '一级分类A',
    children: [
      {
        id: 2,
        label: '二级分类A',
        children: [
          {id: 3, label: '三级分类A'},
          {id: 4, label: '三级分类B'}
        ]
      },
      {
        id: 5,
        label: '二级分类B'
      },
      {
        id: 6,
        label: '二级分类C',
        children: [
          {id: 7, label: '三级分类A'},
          {id: 8, label: '三级分类B'}
        ]
      }
    ]
  },
  {
    id: 9,
    label: '一级分类B',
    children: [
      {
        id: 10,
        label: '二级分类A',
        children: [
          {id: 11, label: '三级分类A'},
          {id: 12, label: '三级分类B'}
        ]
      },
      {
        id: 13,
        label: '二级分类B',
        children: [
          {id: 14, label: '三级分类A'},
          {id: 15, label: '三级分类B'}
        ]
      }
    ]
  },
  {
    id: 16,
    label: '一级分类C',
    children: [
      {
        id: 17,
        label: '二级分类A',
        children: [
          {id: 18, label: '三级分类A'},
          {id: 19, label: '三级分类B'}
        ]
      },
      {
        id: 20,
        label: '二级分类B'
      }
    ]
  }
])

// 树形引用
const treeRef = ref(null)

// 当前选中节点
const currentNode = ref(null)

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref('add')
const formData = reactive({
  name: '',
  parentId: null
})
const parentName = ref('')

// 表单校验规则
const rules = {
  name: [
    {required: true, message: '请输入分类名称', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ]
}

// 获取节点层级
const getNodeLevel = (node) => {
  let level = 0
  let currentNode = node
  while (currentNode.parent && currentNode.parent.level !== undefined) {
    level++
    currentNode = currentNode.parent
  }
  return level
}

// 节点点击事件
const nodeClick = (data) => {
  currentNode.value = data
}

// 新增分类
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  formData.name = ''

  if (currentNode.value) {
    // 如果已选中节点，获取其父节点信息
    if (currentNode.value && currentNode.value.id) {
      formData.parentId = currentNode.value.id
      parentName.value = currentNode.value.label
    } else {
      // 如果没有父节点，说明是顶级节点
      formData.parentId = null
      parentName.value = '未分类'
    }
  } else {
    // 未选中任何节点时，默认父级为未分类
    formData.parentId = null
    parentName.value = '未分类'
  }
}

// 编辑分类
const handleEdit = () => {
  if (!currentNode.value) {
    ElMessage.warning('请选择要编辑的分类')
    return
  }

  dialogType.value = 'edit'
  dialogVisible.value = true

  // 编辑时带出当前分类信息
  formData.name = currentNode.value.label
  formData.parentId = currentNode.value.id

  // 获取父节点信息
  const parentNode = treeRef.value.getNode(currentNode.value).parent
  parentName.value = parentNode.data.label || '顶级分类'
}

// 检查整个树中是否存在重复名称
const checkDuplicateLabelInTree = (nodes, name, excludeId = null) => {
  for (const node of nodes) {
    // 排除当前正在编辑的节点
    if (node.id !== excludeId && node.label === name) {
      return true
    }
    // 递归检查子节点
    if (node.children && node.children.length) {
      if (checkDuplicateLabelInTree(node.children, name, excludeId)) {
        return true
      }
    }
  }
  return false
}

// 修改保存操作
const handleSave = async () => {
  formRef.value.validate(async (valid) => {
    if (!valid) {
      return
    }

    try {
      // 检查是否存在重复名称（编辑时排除当前节点）
      const isDuplicate = checkDuplicateLabelInTree(
        treeData.value, 
        formData.name, 
        dialogType.value === 'edit' ? currentNode.value.id : null
      )

      if (isDuplicate) {
        ElMessage.warning('分类名称已存在')
        return
      }

      if (dialogType.value === 'add') {
        // 检查层级
        const parentNode = formData.parentId ? treeRef.value.getNode(formData.parentId) : null
        const currentLevel = parentNode ? getNodeLevel(parentNode) : 0

        if (currentLevel >= 4) {
          ElMessage.warning('至多建立4级分类')
          return
        }

        // 添加新节点
        const newNode = {
          id: Date.now(),
          label: formData.name,
          children: []
        }

        if (formData.parentId) {
          const parentNode = treeRef.value.getNode(formData.parentId)
          if (!parentNode.data.children) {
            parentNode.data.children = []
          }
          parentNode.data.children.push(newNode)
        } else {
          if (!treeData.value[0].children) {
            treeData.value[0].children = []
          }
          treeData.value[0].children.push(newNode)
        }
      } else {
        // 编辑节点
        currentNode.value.label = formData.name
      }

      dialogVisible.value = false
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
    } catch (error) {
      console.error(error)
      ElMessage.error('操作失败')
    }
  })
}

// 弹窗关闭时重置表单
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  formData.name = ''
  formData.parentId = null
  parentName.value = ''
}

// 删除分类
const handleDelete = () => {
  if (!currentNode.value) {
    ElMessage.warning('请选择要删除的分类')
    return
  }
  const node = treeRef.value.getNode(currentNode.value)
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex(d => d.id === currentNode.value.id)
  children.splice(index, 1)
  currentNode.value = null
  ElMessage.success('删除成功')
}

// 搜索关键词
const searchKeyword = ref('')

// 搜索并高亮节点
const handleSearch = (value) => {
  if (!value) {
    // 清空搜索时重置高亮
    treeRef.value?.setCurrentKey(null)
    return
  }

  // 递归查找节点
  const findNode = (nodes) => {
    for (const node of nodes) {
      if (node.label.toLowerCase().includes(value.toLowerCase())) {
        // 找到匹配节点，设置高亮并展开父节点
        console.log(node)
        treeRef.value?.setCurrentKey(node.id)
        return true
      }
      if (node.children && node.children.length) {
        if (findNode(node.children)) {
          return true
        }
      }
    }
    return false
  }

  // 执行搜索
  if (!findNode(treeData.value)) {
    ElMessage.info('未找到匹配的分类')
    treeRef.value?.setCurrentKey(null)
  }
}

// 其他功能保持不变
const handleImport = () => {
  ElMessage.success('点击了导入按钮')
}
const handleExport = () => {
  ElMessage.success('点击了导出按钮')
}
const handleViewLog = () => {
  ElMessage.success('点击了日志按钮')
}

// 操作按钮配置
const buttonsConfig = ref({
  add: {visible: true, order: 1, type: 'success'},
  edit: {visible: true, order: 2},
  delete: {visible: true, order: 3, type: 'danger'},
  import: {visible: false, order: 4},
  export: {visible: false, order: 5},
  viewLog: {visible: true, order: 6},
  enable: {visible: false, order: 2},
  disable: {visible: false, order: 3},
})

// 二次确认
const confirmDialogVisible = ref(false)
const currentAction = ref('')
const cancelConfirm = () => {
}
const confirmAction = () => {
}

const formRef = ref(null)
</script>


<style scoped lang="scss">
.category-tab {
  .operation-bar {
    margin-bottom: 0;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    align-items: flex-start;
    .search-box {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-left: auto;

      .search-input {
        width: 230px;
      }
    }
  }

  .main-content {
    background: #fff;
    padding: 0 20px;
    border-radius: 4px;
    min-height: 400px;

    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }
  }
}
</style> 